<template>
	<div class="app-container">
		<el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
			<el-form-item label="事件类型" prop="dailyTaskEventId">
				<!--<el-input v-model="queryParams.dailyTaskEventId" placeholder="请输入事件类型" clearable size="small" @keyup.enter.native="handleQuery" />-->
				<el-select v-model="queryParams.dailyTaskEventId" placeholder="请选择事件类型">
					<el-option v-for="item in Eventlist" :key="item.id" :label="item.eventName" :value="item.id" />
				</el-select>
			</el-form-item>
			<!--<el-form-item label="开始时间" prop="startTime">
				<el-date-picker clearable size="small" style="width: 200px" v-model="queryParams.startTime" type="date" value-format="yyyy-MM-dd" placeholder="选择开始时间">
				</el-date-picker>
			</el-form-item>
			<el-form-item label="结束时间" prop="taskEndTime">
				<el-date-picker clearable size="small" style="width: 200px" v-model="queryParams.taskEndTime" type="date" value-format="yyyy-MM-dd" placeholder="选择结束时间">
				</el-date-picker>
			</el-form-item>-->
			<el-form-item label="任务状态" prop="taskStatus">
				<el-select v-model="queryParams.taskStatus" placeholder="请选择任务状态" clearable size="small">
					<el-option v-for="dict in taskstatus" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['manager:dailyTask:add']">新增</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['manager:dailyTask:edit']">修改</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['manager:dailyTask:remove']">删除</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['manager:dailyTask:export']">导出</el-button>
			</el-col>
			<right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
		</el-row>

		<el-table v-loading="loading" :data="dailyTaskList" @selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55" align="center" />
			<el-table-column label="主键" align="center" prop="id" />
			<el-table-column label="事件类型" align="center" prop="dailyTaskEventId" :formatter="EventFormat" />
			<!--<el-table-column label="开始时间" align="center" prop="startTime" width="180">
				<template slot-scope="scope">
					<span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
				</template>
			</el-table-column>
			<el-table-column label="结束时间" align="center" prop="taskEndTime" width="180">
				<template slot-scope="scope">
					<span>{{ parseTime(scope.row.taskEndTime, '{y}-{m}-{d}') }}</span>
				</template>
			</el-table-column>-->
			<el-table-column label="描述" align="center" prop="taskRemark" />
			<el-table-column label="任务状态" align="center" prop="taskStatus" :formatter="statusFormat" />
			<el-table-column label="定时开关" align="center">
        <template slot-scope="scope" v-if="scope.row.jobStatus != null">
          <el-switch
            v-model="scope.row.jobStatus"
            :active-value="0"
            :inactive-value="1"
            @change="handleStatusChange(scope.row,scope.row.id)"
          ></el-switch>
        </template>
      </el-table-column>
			<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
				<template slot-scope="scope">
					<el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['manager:dailyTask:edit']">修改</el-button>
					<el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['manager:dailyTask:remove']">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

		<!-- 添加或修改日常任务对话框 -->
		<el-dialog :title="title" :visible.sync="open" width="800px" append-to-body :beforeClose="cancel" :closeOnClickModal="false">
			<el-form ref="form" :model="form" :rules="rules" label-width="80px">
				<el-form-item label="事件类型" prop="dailyTaskEventId">
					<!--<el-input v-model="form.dailyTaskEventId" placeholder="请输入事件类型" />-->
					<el-select v-model="form.dailyTaskEventId" placeholder="请输入事件类型" @change="TaskEventChange">
						<el-option v-for="item in Eventlist" :key="item.id" :label="item.eventName" :value="item.id" />
					</el-select>
				</el-form-item>
				<!--<el-form-item label="人员">
					<el-cascader v-model="form.personIdList" :options="treeoptions" :props="props" clearable :show-all-levels="false" style="width: 100%;"></el-cascader>
				</el-form-item>-->
				<el-form-item label="人员名称">
					<el-input v-model="form.persons" @focus="perfocus" placeholder="请选择人员名称"></el-input>
				</el-form-item>
				<!--<el-form-item label="开始时间" prop="startTime" style="width: 49%;display: inline-block;">
					<el-date-picker clearable size="small" style="width: 200px" v-model="form.startTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择开始时间">
					</el-date-picker>
				</el-form-item>
				<el-form-item label="结束时间" prop="taskEndTime" style="width: 49%;display: inline-block;">
					<el-date-picker clearable size="small" style="width: 200px" v-model="form.taskEndTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择结束时间">
					</el-date-picker>
				</el-form-item>-->
				<el-form-item label="描述" prop="taskRemark">
					<el-input v-model="form.taskRemark" :rows="5" type="textarea" placeholder="请输入内容" />
					<el-checkbox-group v-model="checkList" @change="checkchange">
						<template v-for="item in Remarklist">
							<el-col :span="12">
								<el-checkbox :label="item.actionName">{{ item.actionName }}</el-checkbox>
							</el-col>
						</template>
					</el-checkbox-group>
				</el-form-item>
				<el-form-item label="执行类型">
					<el-radio-group v-model="form.taskPerformType">
						<el-radio :label="0">立即执行</el-radio>
						<el-radio :label="1">单次执行</el-radio>
						<el-radio :label="2">定时执行</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item v-if="form.taskPerformType == 1" label="单次时间" style="width: 49%;display: inline-block;">
					<el-date-picker v-model="form.executeType.once.dateTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期时间">
					</el-date-picker>
				</el-form-item>
				<el-form-item v-if="form.taskPerformType == 2" label="定时类型">
					<el-radio-group v-model="form.executeType.timing.timingType">
						<el-radio :label="0">每天</el-radio>
						<el-radio :label="1">每周</el-radio>
						<el-radio :label="2">每月</el-radio>
					</el-radio-group>
				</el-form-item>
				<div v-if="form.taskPerformType == 2">
					<el-form-item v-if="form.executeType.timing.timingType == 0" label="时间" style="width: 49%;display: inline-block;">
						<el-time-picker v-model="form.executeType.timing.everyday.time" value-format="HH:mm:ss" placeholder="选择时间">
						</el-time-picker>
					</el-form-item>
					<el-form-item v-if="form.executeType.timing.timingType == 1" label="星期">
						<el-radio-group v-model="form.executeType.timing.weekly.severalWeeks">
							<el-radio :label="2">星期一</el-radio>
							<el-radio :label="3">星期二</el-radio>
							<el-radio :label="4">星期三</el-radio>
							<el-radio :label="5">星期四</el-radio>
							<el-radio :label="6">星期五</el-radio>
							<el-radio :label="7">星期六</el-radio>
							<el-radio :label="1">星期日</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item v-if="form.executeType.timing.timingType == 1" label="时间">
						<el-time-picker v-model="form.executeType.timing.weekly.time" value-format="HH:mm:ss" placeholder="选择时间">
						</el-time-picker>
					</el-form-item>
					<el-form-item v-if="form.executeType.timing.timingType == 2" label="天数">
						<el-radio-group v-model="form.executeType.timing.monthly.day">
							<template v-for="item in 31" style="margin: 5px 0;">
								<el-col :span="3">
									<el-radio :label="item">{{ item }}</el-radio>
								</el-col>
							</template>
						</el-radio-group>
					</el-form-item>
					<el-form-item v-if="form.executeType.timing.timingType == 2" label="时间">
						<el-time-picker v-model="form.executeType.timing.monthly.time" value-format="HH:mm:ss" placeholder="选择时间">
						</el-time-picker>
					</el-form-item>
				</div>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>
		<el-dialog title="人员选择" :visible.sync="outerVisible1" width="600px" top="200px">
			<el-input placeholder="输入关键字进行过滤" v-model="filterText1">
			</el-input>

			<el-tree class="filter-tree" :data="treeoptions" :props="defaultProps1" :default-checked-keys="defaultKeys" node-key="id" show-checkbox :filter-node-method="filterNode" ref="tree1" style="margin-top: 10px;">
			</el-tree>
			<div slot="footer" class="dialog-footer">
				<el-button @click="outerVisible1 = false">取 消</el-button>
				<el-button type="primary" @click="getCheckedNodes1">保存</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import { listDailyTask, getDailyTask, delDailyTask, addDailyTask, updateDailyTask, exportDailyTask, getDailyTaskAll, getPersonTree, statusChanges } from "@/api/task/dailyTask";

	export default {
		name: "DailyTask",
		data() {
			return {
				// 遮罩层
				loading: true,
				// 选中数组
				ids: [],
				// 非单个禁用
				single: true,
				// 非多个禁用
				multiple: true,
				// 显示搜索条件
				showSearch: true,
				// 总条数
				total: 0,
				// 日常任务表格数据
				dailyTaskList: [],
				// 弹出层标题
				title: "",
				// 是否显示弹出层
				open: false,
				// 查询参数
				queryParams: {
					pageNum: 1,
					pageSize: 10,
					dailyTaskEventId: null,
					taskRemark: null,
					cronExpression: null,
					cronAnalysis: null,
					taskStatus: null
				},
				// 表单参数
				form: {},
				// 表单校验
				rules: {},
				taskstatus: [],
				dailytype: "0",
				Eventlist: [],
				checkList: [],
				Remarklist: [],
				props: {
					multiple: true,
					value: 'id',
					label: 'name',
					emitPath: false,
					checkStrictly: true
				},
				treeoptions: [],

				defaultKeys: [], // 默认选中的节点
				outerVisible1: false,
				filterText1: '',
				defaultProps1: {
					children: 'children',
					label: 'name'
				}
			};
		},
		created() {
			this.getList();
			this.getDicts('daily_task_status').then(response => {
				this.taskstatus = response.data;
			});
			getDailyTaskAll().then(response => {
				this.Eventlist = response.data;
				console.log(this.Eventlist)
			});
			getPersonTree().then(response => {
				this.treeoptions = response.data;
				console.log(response.data)
			});
		},
		watch: {
			filterText1(val) {
				this.$refs.tree1.filter(val);
			}
		},
		methods: {
			handleStatusChange(row,id) {
        let that = this;
				console.log(row,id)
				let text = row.jobStatus === "0" ? "启用" : "停用";
				this.$confirm('确认要"' + text + '"任务吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
       }).then(function() {
          statusChanges({
						"dailyTaskId": id,
	 					"status": row.jobStatus
					}).then(response => {
						that.getList();
					});
        }).catch(function() {
          row.jobStatus = row.jobStatus === "0" ? "1" : "0";
        })
				
			},
			perfocus(){
				this.outerVisible1 = true;
			},
			filterNode(value, data) {
				if(!value) return true;
				return data.label.indexOf(value) !== -1;
			},
			getCheckedNodes1() {
				var dataa = this.$refs.tree1.getCheckedNodes();
				console.log(dataa)
				var arr = [];
				var ids = [];
				for(var i = 0; i < dataa.length; i++) {
					if(dataa[i].children == null) {
						ids.push(dataa[i].id);
						arr.push(dataa[i].name);
					}
				}
				this.form.personIdList = ids;
				this.form.persons = arr.join(',');
				this.outerVisible1 = false;
			},
			/** 查询日常任务列表 */
			getList() {
				this.loading = true;
				listDailyTask(this.queryParams).then(response => {
					console.log(response.rows, 'list')
					this.dailyTaskList = response.rows;
					this.total = response.total;
					this.loading = false;
				});
			},
			// 字典翻译
			statusFormat(row, column) {
				return this.selectDictLabel(this.taskstatus, row.taskStatus);
			},
			EventFormat(row, column) {
				for(var i = 0; i < this.Eventlist.length; i++) {
					if(this.Eventlist[i].id == row.dailyTaskEventId) {
						return this.Eventlist[i].eventName;
					}
				}
			},
			// 取消按钮
			cancel() {
				console.log(this.$refs.tree1)
				if(this.$refs.tree1){
					this.$refs.tree1.setCheckedNodes([]);
				}				
				this.open = false;
				this.reset();
			},
			// 表单重置
			reset() {
				this.form = {
					id: null,
					dailyTaskEventId: null,
					//					startTime: null,
					//					taskEndTime: null,
					taskRemark: null,
					cronExpression: null,
					cronAnalysis: null,
					createTime: null,
					taskStatus: 0,
					taskPerformType: 0,
					personIdList: [],
					persons: '',
					executeType: {
						"once": {
							"dateTime": ""
						},
						"timing": {
							"timingType": 0,
							"everyday": {
								"time": ""
							},
							"weekly": {
								"severalWeeks": "",
								"time": ""
							},
							"monthly": {
								"day": "",
								"time": ""
							}
						}
					}
				};
				
				this.defaultKeys = [];
				this.checkList = [];
				this.Remarklist = [];
				this.resetForm("form");
			},
			/** 搜索按钮操作 */
			handleQuery() {
				this.queryParams.pageNum = 1;
				this.getList();
			},
			/** 重置按钮操作 */
			resetQuery() {
				this.resetForm("queryForm");
				this.handleQuery();
			},
			// 多选框选中数据
			handleSelectionChange(selection) {
				this.ids = selection.map(item => item.id)
				this.single = selection.length !== 1
				this.multiple = !selection.length
			},
			/** 新增按钮操作 */
			handleAdd() {
				this.reset();
				this.open = true;
				this.title = "添加日常任务";
			},
			/** 修改按钮操作 */
			handleUpdate(row) {
				this.reset();
				const id = row.id || this.ids
				getDailyTask(id).then(response => {
					this.form = response.data;
					this.defaultKeys = response.data.personIdList;
					this.form.persons = response.data.personNameList.join(',');
					this.open = true;
					this.title = "修改日常任务";
				});
			},
			/** 提交按钮 */
			submitForm() {
				this.$refs["form"].validate(valid => {
					if(valid) {
						//						console.log(this.form)
						if(this.form.id != null) {
							updateDailyTask(this.form).then(response => {								
								this.$refs.tree1.setCheckedNodes([]);
								this.msgSuccess("修改成功");
								this.open = false;
								this.getList();
							});
						} else {
							addDailyTask(this.form).then(response => {				
								this.$refs.tree1.setCheckedNodes([]);
								this.msgSuccess("新增成功");
								this.open = false;
								this.getList();
							});
						}
					}
				});
			},
			/** 删除按钮操作 */
			handleDelete(row) {
				const ids = row.id || this.ids;
				this.$confirm('是否确认删除日常任务编号为"' + ids + '"的数据项?', "警告", {
					confirmButtonText: "确定",
					cancelButtonText: "取消",
					type: "warning"
				}).then(function() {
					return delDailyTask(ids);
				}).then(() => {
					this.getList();
					this.msgSuccess("删除成功");
				})
			},
			/** 导出按钮操作 */
			handleExport() {
				const queryParams = this.queryParams;
				this.$confirm('是否确认导出所有日常任务数据项?', "警告", {
					confirmButtonText: "确定",
					cancelButtonText: "取消",
					type: "warning"
				}).then(function() {
					return exportDailyTask(queryParams);
				}).then(response => {
					this.download(response.msg);
				})
			},
			TaskEventChange(e) {
				console.log(e);
				for(var i = 0; i < this.Eventlist.length; i++) {
					if(this.Eventlist[i].id == e) {
						this.Remarklist = this.Eventlist[i].dailyTaskEventActionList;
					}
				}
			},
			checkchange(e) {
				this.form.taskRemark = this.checkList.join(',');
			}
		}
	};
</script>